package com.wink_172.activity;


import static com.wink_172.library.model.Constants.local_path;
import static com.wink_172.library.utils.CommonUtils.downLoadFile;
import static com.wink_172.model.Constants.SCENE_DOWN_LOAD_LIST2;
import static com.wink_172.model.Constants.SCENE_DOWN_LOAD_STATUS_LIST;
import static com.wink_172.model.Constants.down_loading;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.wink_172.adapter.HBomeListAdapter;
import com.wink_172.commons.BuildConfig;
import com.wink_172.commons.R;
import com.wink_172.commons.databinding.ActivityImageListBinding;
import com.wink_172.library.activity.PlayImageActivity;
import com.wink_172.library.activity.SmartActivity;
import com.wink_172.library.adapter.HomeListAdapter;
import com.wink_172.library.model.BaseDataItem;
import com.wink_172.library.model.Constants;
import com.wink_172.library.model.json.FileData;
import com.wink_172.library.utils.AlbumNotifyHelper;
import com.wink_172.library.utils.CommonUtils;
import com.wink_172.library.utils.DateUtil;
import com.wink_172.library.utils.FileUtil;
import com.wink_172.library.utils.HttpRequest;
import com.wink_172.library.utils.MMKVTool;
import com.wink_172.library.utils.TencentCosUtils;
import com.wink_172.library.view.ActionBarView;

import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 下载目录文件
 */
public class DownloadListActivity extends SmartActivity {

    public ActivityImageListBinding binding;

    public static void startActivity(Activity context, Object... args) {
        Intent intent = new Intent(context, DownloadListActivity.class);
        int mode = (Integer) args[0];


        intent.putExtra(com.wink_172.library.model.Constants.PARAM_DATA1, mode);

        switch (mode) {
            case 0: {//普通

                break;
            }
            case 1: {//自动选择下载
                break;
            }
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_image_list);

        initView();
        init();
    }

    @Override
    public void handlerCallBack(@Nullable Message msg) {
        super.handlerCallBack(msg);

        if (msg.what == com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal()) {
            down_loading = false;
            binding.listView2.setBackgroundColor(x.app().getResources().getColor(R.color.transparent));
            getImageList();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        down_loading = false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        first_time = true;

        init();
    }

    void init() {
        setMode(getIntent().getIntExtra(com.wink_172.library.model.Constants.PARAM_DATA1, 0));
        getImageList();
    }

    public void initView() {
        binding.selectMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                homeListAdapter.setListSelect(true);
                homeListAdapter.notifyDataSetChanged();
            }
        });

        binding.unselectMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();

                List<Object> list = homeListAdapter.getDataList();
                homeListAdapter.setListSelect(false);
                for (int i = 0; i < list.size(); i++) {
                    BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                    baseDataItem.setSelect(false);

                }
                homeListAdapter.notifyDataSetChanged();
            }
        });

        binding.selectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                List<Object> list = homeListAdapter.getDataList();
                homeListAdapter.setListSelect(true);
                for (int i = 0; i < list.size(); i++) {
                    BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                    baseDataItem.setSelect(true);

                }
                homeListAdapter.notifyDataSetChanged();

            }
        });

        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                List<Object> list = homeListAdapter.getDataList();


                boolean need_delete = false;
                if (homeListAdapter.isListSelect()) {
                    for (int i = 0; i < list.size(); i++) {

                        BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                        if (baseDataItem.getSelect()) {
                            FileData single_file = (FileData) baseDataItem.getData();
                            single_file.local_url = local_path + FileUtil.Companion.getFileNameWithSuffix(single_file.web_url);
                            Log.e(TAG, "正在删除: ====>>" + single_file.local_url);
                            FileUtil.Companion.delete(single_file.local_url);
                            need_delete = true;
                        }

                    }
                }


                if (need_delete) {
                    x.task().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            getImageList();

                        }
                    }, 300);
                }


            }
        });


        binding.down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                List<Object> list = homeListAdapter.getDataList();

                for (int i = 0; i < list.size(); i++) {
                    BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                    if (baseDataItem.getSelect()) {
                        FileData single_file = (FileData) baseDataItem.getData();

                        if (FileUtil.Companion.isCacheFileExist(single_file.local_url)) {
//
                        } else {
                            Log.e(TAG, "正在下载: ====>>" + single_file.web_url);
                            down_loading = true;

                            downLoadFile(single_file.web_url, single_file.local_url,
                                    new com.wink_172.library.callback.ICallback() {
                                        @Override
                                        public void onSendEvent(int event, @NonNull Object... objects) {


                                            if (event == Constants.EventEnum.网络请求成功.ordinal()) {

                                                String ext = FileUtil.Companion.getExtensionName(single_file.local_url);
                                                if (ext.contains("jpg") ||
                                                        ext.contains("gif") ||
                                                        ext.contains("mp4") ||
                                                        ext.contains("jpeg")) {
                                                    AlbumNotifyHelper.insertImageToMediaStore(x.app(), single_file.local_url, System.currentTimeMillis());
                                                } else {
                                                }
                                                Log.e(TAG, "下载成功: ====>>" + single_file.local_url);

                                                getHandle().removeMessages(com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal());
                                                getHandle().sendEmptyMessageDelayed(com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal(), 2000);

                                            } else if (event == Constants.EventEnum.下载进度更新.ordinal()) {
                                                //请注意如果下载链接包含中文或特殊字符，不会到这里，也不会下载完成
                                                down_loading = true;

                                                long total = (long) objects[0];
                                                long current = (long) objects[1];
                                                String web_url = (String) objects[2];

                                                String str = FileUtil.Companion.getFileNameWithSuffix(web_url) + "(" + current / 1024 + "kb/" + total / 1024 + "kb)";
                                                initCurrentStatusList(str);
                                                binding.listView2.setBackgroundColor(x.app().getResources().getColor(R.color.color_pan5));
                                                getHandle().removeMessages(com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal());

                                            } else if (event == Constants.EventEnum.网络请求完成.ordinal()) {
                                                getHandle().removeMessages(com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal());
                                                getHandle().sendEmptyMessageDelayed(com.wink_172.model.Constants.EventEnum.更新下载状态.ordinal(), 2000);

                                            }
                                        }
                                    }
                            );
                        }


                    }
                }

            }


        });
        ((ActionBarView) binding.actionBar).content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImageList();
            }
        });

        ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_back, "", "去下载页");

        ((ActionBarView) binding.actionBar).setCallback(new ActionBarView.ICallback() {
            @Override
            public void onSendEvent(int event, String content) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish();

                } else if (event == ActionBarView.RIGHT_BTN) {

                    goDownloadPage();
                }
            }
        });


        List<Object> list = new ArrayList();
        HBomeListAdapter homeListAdapter = new HBomeListAdapter(this, list, binding.listView);
        binding.listView.init(homeListAdapter, false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 6, GridLayoutManager.VERTICAL, false);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
//                if (position < 7 || position > 14) {
//                    return 3;
//                }
                return 2;
            }
        });
        binding.listView.setLayoutManager(gridLayoutManager);


        if (true) {
            List<Object> list2 = new ArrayList();
            HBomeListAdapter homeListAdapter2 = new HBomeListAdapter(this, list2, binding.listView2);
            binding.listView2.init(homeListAdapter2, false);
            GridLayoutManager gridLayoutManager2 = new GridLayoutManager(getActivity(), 1, GridLayoutManager.VERTICAL, false);
            gridLayoutManager2.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
//                if (position < 7 || position > 14) {
//                    return 3;
//                }
                    return 1;
                }
            });
            binding.listView2.setLayoutManager(gridLayoutManager2);
        }
    }


    private static final String TAG = "ImageListActivity";

    boolean first_time = true;


    /**
     * 获取文件列表
     */
    private void getImageList() {

        HttpRequest.INSTANCE.get_test_imge_listbb(new com.wink_172.library.callback.ICallback() {
            @Override
            public void onSendEvent(int event, @NonNull Object... objects) {
                if (event == Constants.EventEnum.网络请求成功.ordinal()) {

                    Log.e(TAG, "onSendEvent: ====>>获取列表1");
                    List cc_list = (List) objects[0];
                    initImageList(cc_list);

                    if (getMode() == 1 && first_time) {
                        first_time = false;
                        binding.selectAll.performClick();
                        FileUtil.Companion.createFolder(local_path);
                        x.task().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                binding.down.performClick();
                            }
                        }, 250);

                    }
                }
            }
        });

    }

    public void initImageList(List<FileData> file_list) {
        List<Object> list = new ArrayList<Object>();

        ((ActionBarView) binding.actionBar).content.setText("文件(" + file_list.size() + ")");
        HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
        for (int i = 0; i < file_list.size(); i++) {
            FileData single_file = file_list.get(i);
            BaseDataItem baseDataItem = new BaseDataItem(i, SCENE_DOWN_LOAD_LIST2);


            homeListAdapter.setMOnItemClickListener(new HomeListAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(@Nullable View view, int pos) {

                    if (homeListAdapter.isListSelect()) {
                        BaseDataItem baseDataItem = (BaseDataItem) homeListAdapter.getDataList().get(pos);
                        baseDataItem.setSelect(baseDataItem.getSelect() == false);//反选
                        homeListAdapter.notifyItemChanged(pos);

                    } else {
                        BaseDataItem baseDataItem = (BaseDataItem) homeListAdapter.getDataList().get(pos);
                        FileData single = (FileData) baseDataItem.getData();
                        PlayImageActivity.startActivity(getActivity(), 0, single.local_url);
                    }
                }
            });


            //http://106.52.115.24:8888/down/yLHb3wphzAjX?fname=/wink-172-debug.apk
            //http://106.52.115.24:8081//down/yLHb3wphzAjX?fname=/BiBu_v6.3.apk
            //  https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/share_fd/111.txt
//            String temp = "http://106.52.115.24:8888" + single_file.web_url;
            String temp = "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/share_fd/" + FileUtil.Companion.getFileNameWithSuffix(single_file.web_url);


            single_file.web_url = temp;
            single_file.local_url = local_path + FileUtil.Companion.getFileNameWithSuffix(single_file.web_url);


            baseDataItem.setObjectData(single_file);
            list.add(0, baseDataItem);

        }
        homeListAdapter.setListSelect(homeListAdapter.isListSelect());
        homeListAdapter.swapContent(list);
        homeListAdapter.notifyDataSetChanged();
    }


    /**
     * 下载进度
     */
    public void initCurrentStatusList(String str) {
        List<Object> list = new ArrayList<Object>();

        HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView2.getAdapter();
        BaseDataItem baseDataItem = new BaseDataItem(-1, SCENE_DOWN_LOAD_STATUS_LIST);

        baseDataItem.setContent(str);
        list.add(baseDataItem);

        homeListAdapter.appendContent(list, true);
        homeListAdapter.notifyItemInserted(0);
        binding.listView2.smoothScrollToPosition(0);
    }


    public void goDownloadPage() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        // 设置Intent的类型为任意文件类型
        intent.setType("*/*");

        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {

            Toast.makeText(this, "没有找到可用的文件管理器", Toast.LENGTH_SHORT).show();
        }

    }

}